package com.read.scriptures.manager;

import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.music.player.lib.util.NetUtil;
import com.read.scriptures.app.HuDongApplication;
import com.read.scriptures.bean.FreeBean;
import com.read.scriptures.bean.RespInfo;
import com.read.scriptures.bean.UserInfo;
import com.read.scriptures.bean.UserInfoBean;
import com.read.scriptures.bean.UserNetInfo;
import com.read.scriptures.config.PreferenceConfig;
import com.read.scriptures.config.ZConfig;
import com.read.scriptures.event.LoginOutEvent;
import com.read.scriptures.event.RefreshUserInfoEvent;
import com.read.scriptures.http.okhttp.HttpCallback;
import com.read.scriptures.http.okhttp.OkHttpUtils;
import com.read.scriptures.util.GsonUtils;
import com.read.scriptures.util.NetConnectUtil;
import com.read.scriptures.util.SharedUtil;
import com.read.scriptures.util.StringUtil;
import com.read.scriptures.util.SystemUtils;
import com.read.scriptures.util.ThreadUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

/**
 * 账户管理类
 * Created by Administrator.
 * Datetime: 2015/6/26.
 * Email: lgmshare@mgail.com
 */
public class AccountManager {

    private final String SP_USER_INFO = "sp_user_info";
    //微信授权的code
    public static final String SP_WEIXIN_LOGIN_CODE = "sp_weixin_login_code";

    private UserInfo userInfo;
    //是否登录
    private boolean isLogin = false;

    public interface IAccountManagerListener {
        void requestResult(boolean isSuccess, String errorMsg);
    }

    //单例
    private static AccountManager mInstance;


    private AccountManager() {
        init();
    }

    public String getAudioShareLink() {
        return audioShareLink;
    }

    public void setAudioShareLink(String audioShareLink) {
        this.audioShareLink = audioShareLink;
    }

    private String audioShareLink;

    /**
     * 初始化
     *
     * @return
     */
    public static AccountManager getInstance() {
        if (mInstance == null) {
            mInstance = new AccountManager();
        }
        return mInstance;
    }

    public boolean levelAvailable(String vipName) {
        if (userInfo != null) {
            refreshUserInfo(null);
            return userInfo.levelAvailable(vipName);
        } else {
            return false;
        }
    }

    private void init() {
        initUserInfo();
        isLogin = (userInfo != null);
    }

    private void saveUserInfo(UserInfo userInfo) {
        if (userInfo != null) {
            SharedUtil.putString(SP_USER_INFO, GsonUtils.objectToStr(userInfo));
//            //更新过期时间
//            long maturityTime = userInfo.getLevel().get(0).getExpire();
//            PreferenceConfig.saveActivationTime(HuDongApplication.getInstance(), maturityTime);
//            //第一次安装
//            PreferenceConfig.saveFirstInstallTime(HuDongApplication.getInstance(), TimeUtils.getNowStamp());
//            if (maturityTime > TimeUtils.getNowStamp()) {
//                HuDongApplication.getInstance().setIsAppActivate(true);
//            } else if (maturityTime == -1) {
//                HuDongApplication.getInstance().setIsAppActivate(true);
//            } else {
//                HuDongApplication.getInstance().setIsAppActivate(false);
//            }
//            if (PreferenceConfig.getFreeActiveTimeOpen(HuDongApplication.getInstance())) {//保存免费接口
//                HuDongApplication.getInstance().setIsAppActivate(true);
//            }
            //通知界面刷新Lo
            EventBus.getDefault().post(new RefreshUserInfoEvent());

        }
        isLogin = (userInfo != null);
    }

    private UserInfo initUserInfo() {
        String userJson = SharedUtil.getString(SP_USER_INFO);
//        userJson = "{\"create_time\":1608611419,\"level\":[{\"expire\":1636707272,\"format\":\"44天19小时25分38秒\",\"text\":\"普通会员\",\"time\":\"2021-11-12 16:54:32\",\"val\":\"v1\"}],\"sequence\":\"oBz-wxMaiYw3eFho63Xb7OYDYKco\",\"token\":\"CECrOtQf0eWNm6inR8HghuYJeffVOu4ITIkAl4Jz/6mmJ0ggyOIg/HAj+zQy957d7unI3g0XX/zS9t2TKQN/ioEoF/uA\",\"username\":\"1908645997\",\"wxAccessToken\":\"48_RbiSsA4oBSCDTb1C4qIxsaniLiIhyA0hrMXKL7AcL-WaSb8isEDfXm-_3vSSvu67DdqcKCOVZ1rMreLB8kRmTizFYsb7LSU0hjFAUAFjiSs\",\"wxOpenId\":\"oBz-wxMaiYw3eFho63Xb7OYDYKco\",\"wxRefreshToken\":\"48_PDJNry_lY-qHaN73GKx-u8d6Q2l5SPsMTIZcsFydxuOEDngzGJD2iFjWqZ2DQxekbsJrNDYb3kH2j3JgQfpcK4385vmPU89ZDnbP_XR0Vug\"}";
//        Log.w("TTT","userJson:"+userJson);
//        userJson = "{\"create_time\":1608611419,\"level\":[{\"expire\":0,\"format\":\"\",\"text\":\"普通会员\",\"time\":\"2021-01-25 22:57:17\",\"val\":\"v0\"}],\"sequence\":\"oBz-wxMaiYw3eFho63Xb7OYDYKco\",\"token\":\"Dkz+ONZO3eqNm6inR8HghuYJeffVOu4ITIkAl4Jz/6mmJ0ggyOIg/HAj+zQy957d7unI3g0XX/zS9t2TKwJ9i48gGPiA\",\"username\":\"1908645997\",\"wxAccessToken\":\"41_i-kFdGvi2vQbrLYd812PFOS3KNAau2Jljkh9ipAtkT0RoF_vs_s9ENCnwjtlfEMB1W_JprjfDYhCYeOOaNMXy0tkm3_W3cvT0AK7yxUArsQ\",\"wxOpenId\":\"oBz-wxMaiYw3eFho63Xb7OYDYKco\",\"wxRefreshToken\":\"41_pWgSOAAXjuR5zLF96VN8Yl-aCPMHopEUI5v0E9FAoaNN1p0X7Y07X5uA_Lm2EgZLuSzuw4fVl_F71SuCJWrVRoRdE-_EKL9xyPf79SjDwpk\"}";
//        SharedUtil.putString(SP_USER_INFO,userJson);
        if (!StringUtil.isEmpty(userJson)) {
            userInfo = (UserInfo) GsonUtils.jsonToObj(userJson, UserInfo.class);
        }
        return userInfo;
    }

    public boolean isLogin() {
        return isLogin;
    }

    public UserInfo getUserInfo() {
        return userInfo;
    }


    /**
     * 退出登录
     */
    public void loginOut(boolean isTokenInvalid, String errMsg) {
        isLogin = false;
        userInfo = null;
        SharedUtil.remove(SP_USER_INFO);
        SharedUtil.remove(SP_WEIXIN_LOGIN_CODE);
        EventBus.getDefault().post(new LoginOutEvent(isTokenInvalid, errMsg));
    }

    public void loginOut(boolean isTokenInvalid) {
        loginOut(isTokenInvalid, "");
    }


    /**
     * 后台登录接口
     */
    public void loginService(String code, final IAccountManagerListener listener) {
        HashMap<String, String> params = new HashMap<>();
        params.put("code", code);
        params.put("version", String.valueOf(SystemUtils.getVersionName(HuDongApplication.getInstance())));
        NetUtil.get(ZConfig.USER_WX_LOGIN, params, new NetUtil.CallBack() {
            @Override
            public void onSuccess(String t) {
                UserInfoBean result = new Gson().fromJson(t, UserInfoBean.class);
                if (result != null && result.data != null) {
                    UserNetInfo userNetInfo = result.data;
                    userInfo = new UserInfo();
                    userInfo.setWxAccessToken(userNetInfo.getAccess_token());
                    userInfo.setWxRefreshToken(userNetInfo.getRefresh_token());
                    userInfo.setWxOpenId(userNetInfo.getOpenid());
                    userInfo.setLevel(userNetInfo.getLevel());
                    userInfo.setToken(userNetInfo.getToken());
                    userInfo.setUsername(userNetInfo.getUsername());
                    userInfo.setSequence(userNetInfo.getSequence());
                    userInfo.setCreate_time(userNetInfo.getCreate_time());
                    saveUserInfo(userInfo);
                    if (listener != null) {
                        listener.requestResult(true, "");
                    }
                    //成功,查询微信信息
                    refreshUserInfo(null);
                } else {
                    if (listener != null) {
                        listener.requestResult(false, "数据解析错误");
                    }
                }
            }

            @Override
            public void onError(String t) {
                super.onError(t);
                listener.requestResult(false, t);
            }
        });
    }

    /**
     * 登录的情况下刷新用户信息
     */
    public void refreshUserInfo(final IAccountManagerListener listener) {
        ThreadUtil.doOnOtherThread(new Runnable() {
            @Override
            public void run() {
                if (userInfo != null) {
                    HashMap<String, String> params = new HashMap<>();
                    params.put("token", userInfo.getToken());
                    params.put("version", String.valueOf(SystemUtils.getVersionName(HuDongApplication.getInstance())));
                    OkHttpUtils.getInstance().get(ZConfig.REFRESH_USER_INFO, params, new HttpCallback<RespInfo<UserNetInfo>>() {
                        @Override
                        public void onSuccess(RespInfo<UserNetInfo> result) {
                            if (result != null) {
                                try {
                                    UserNetInfo userNetInfo = result.getData();
                                    userInfo.setLevel(userNetInfo.getLevel());
                                    userInfo.setToken(userNetInfo.getToken());
                                    userInfo.setUsername(userNetInfo.getUsername());
                                    userInfo.setSequence(userNetInfo.getSequence());
                                    userInfo.setCreate_time(userNetInfo.getCreate_time());
                                    saveUserInfo(userInfo);
                                    if (listener != null) {
                                        listener.requestResult(true, "");
                                    }
                                } catch (Exception e) {
                                    if (listener != null) {
                                        listener.requestResult(false, "数据解析错误");
                                    }
                                }
                            }
                        }

                        @Override
                        public void onError(int code, String errorMsg) {
                            if (listener != null) {
                                listener.requestResult(false, errorMsg);
                            }
                        }

                        @Override
                        public void onFinish() {

                        }
                    });
                }
                refreshFreeStatus();
            }
        });
    }

    private void refreshFreeStatus() {
        try {
            String free = NetConnectUtil.getContent(HuDongApplication.getInstance(), ZConfig.FREE_URL, 3);
            if (!StringUtil.isEmpty(free)) {
                JSONObject jsonObject = JSONObject.parseObject(free);
                String data = jsonObject.getString("data");
                if (!StringUtil.isEmpty(data)) {
                    FreeBean freeBean = JSONObject.parseObject(data, FreeBean.class);
                    PreferenceConfig.saveFreeActiveTimeOpen(HuDongApplication.getInstance(), freeBean.isOpen());//保存免费接口
                    PreferenceConfig.saveFreeActiveTimeEnd(HuDongApplication.getInstance(), freeBean.getEnd_time());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getLevelName(String levelType) {
        if (levelType == null) {
            levelType = "";
        } else if (!levelType.toLowerCase().startsWith("v")) {
            levelType = "v" + levelType;
        }
        switch (levelType) {
            case UserInfo.VIP_NORMAL:
                return "普通会员";
            case UserInfo.VIP_HIGH:
                return "高级会员";
            case UserInfo.VIP_SUPPER:
                return "超级会员";
            default:
                return "会员";
        }
    }

}